import React, {Component} from "react";
import {connect} from "react-redux";
import {HomeWrapper} from "../Home/style";
import {MineContainer} from "./style";
import LeftBar from "./LeftBarContaier";
import {renderRoutes} from "react-router-config";
import {Avatar, Button, Col, Form, Input, Row, Tooltip, Upload} from "antd";
import {
    AboutContainer,
    BtnContainer,
    EditContainer,
    HeaderContainer,
    ImageContainer,
    MoreInformationContainer,
    PayContainer,
    PersonalDataContainer,
    VipItemContainer,
    VipItemHeader,
    VipServerContainer
} from "@/component/Mine/PersonalData/style";
import {JVip} from "@/common/Icon/Vip";
import Config from "@/config";
import moment from "moment";
import Http from "@/util/http";
import {Api, queryState, successMsg, warnMsg} from "@/util/global";
import {toBase64} from "@/util/CodeUtils";
import {actions as UserAction} from "@/store/common/user";
import {resetUserInfo, userVipType} from "@/util/UserUtil";
import {getVipServer, payVipService} from "@/api/OnlineVip";
import PolishConfirm from "@/common/Modal/PolishConfirm";
import {editOnlineInfo} from "@/api/SysUserInfo";
import {changeEmail, sendEmailValidation} from "@/api/Common";

class Mine extends Component {
    editForm = React.createRef();

    constructor(props) {
        super(props);
        this.handleOpenVipServer = this.handleOpenVipServer.bind(this);
        this.handleClickEdit = this.handleClickEdit.bind(this);
        this.editElementNode = this.editElementNode.bind(this);
        this.vipServerElementNode = this.vipServerElementNode.bind(this);
        this.handleEdit = this.handleEdit.bind(this);
        this.handlePayVipService = this.handlePayVipService.bind(this);
        this.handleBindEmail = this.handleBindEmail.bind(this);
        this.handleSendEmailCode = this.handleSendEmailCode.bind(this);
        this.handleValueChange = this.handleValueChange.bind(this);
        this.state = {
            fileList: [],
            confirmVisible: false,
            editFormData: {},
            emailCodeTimeOut: null,
            confirmType: null,
            vipServer: [],
            vipServerSelect: null,
            payMethodSelect: null
        }
    }

    handleValueChange(key, e) {
        let {editFormData} = this.state;
        editFormData[key] = e.target ? e.target.value : e;
        this.setState({
            editFormData
        })
        this.editForm.current.setFieldsValue(editFormData)
    }

    handleSendEmailCode() {
        sendEmailValidation(this.state.editFormData.email)
            .then(res => {
                if (res.success) {
                    successMsg("验证码已发送！");
                    this.emailTimer = setInterval(() => {
                        let current = this.state.emailCodeTimeOut;
                        if (current !== null && current !== 0) {
                            this.setState({
                                emailCodeTimeOut: current - 1
                            })
                        } else if (current === null) {
                            this.setState({
                                emailCodeTimeOut: 60
                            })
                        } else {
                            clearInterval(this.emailTimer)
                            this.setState({
                                emailCodeTimeOut: null
                            })
                        }
                    }, 1000)
                }
            })
    }

    handleBindEmail() {
        let params = {
            mailCode: this.state.editFormData.emailValidation,
            email: this.state.editFormData.email
        }
        changeEmail(params).then(res => {
            if (res.success) {
                successMsg("更改邮箱成功！")
                this.setState({confirmType: null, confirmVisible: false});
                resetUserInfo();
            }
        })
    }

    handlePayVipService() {
        if (!this.state.vipServerSelect) {
            warnMsg("您还没选择VIP服务类型！");
            return;
        } else if (!this.state.payMethodSelect) {
            warnMsg("您还没选择支付方式！")
            return;
        }
        let params = {
            vipServerDictId: this.state.vipServerSelect,
            payMethodId: this.state.payMethodSelect
        }
        payVipService(params)
            .then(res => {
                if (res.success) {
                    successMsg(<>
                        <p style={{color: "#999", fontSize: '12px'}}>系统内测阶段，无需真实支付</p>
                        <span>恭喜您开通成功！</span>
                    </>)
                    this.setState({confirmType: null, confirmVisible: false});
                }
                resetUserInfo();
            })
    }

    vipServerElementNode() {
        let time = moment(this.props.user.vipExpireDate).diff(new moment(), 'day');
        if (time > 365) {
            time = "大于" + moment(this.props.user.vipExpireDate).diff(new moment(), 'year') + "年";
        } else if (time > 0) {
            time = time + "天";
        } else {
            time = moment(this.props.user.vipExpireDate).diff(new moment(), 'hour') + "小时";
        }
        return <>
            <VipServerContainer>
                <Row gutter={[3, 20]}>
                    <Col span={12} className={'me'}>
                        <Avatar src={this.props.user.images} size={50} className={'img'}/>
                        <span className={'name'}>{
                            this.props.user.isVip ?
                                "会员剩余：" + time
                                :
                                "欢迎您办理VIP服务！"
                        }</span>
                    </Col>
                    <Col span={12}>
                        <span className={'close'}
                              onClick={() => this.setState({confirmType: null, confirmVisible: false})}>
                            <Config.IconFont type={'icon-guanbi'}/>
                        </span>
                    </Col>
                    <Col span={24}>
                        <h4 style={{color: '#666', padding: '0 5px'}}>
                            VIP服务
                        </h4>
                    </Col>
                    {
                        (() => {
                            let nodes = [];
                            let keys = Object.keys(this.state.vipServer);
                            let unit = null;
                            const iconStyle = {fontSize: '30px', marginRight: '5px', float: 'left'};
                            const selectIconStyle = {
                                position: "absolute",
                                top: '10px',
                                right: '10px',
                                fontSize: "20px",
                                color: '#418cff'
                            };
                            keys.forEach(key => {
                                let current = this.state.vipServer[key];
                                nodes.push(<Col span={(24 / keys.length)} key={current.serverId}>
                                    <VipItemContainer
                                        onClick={() => this.setState({vipServerSelect: current.serverId})}>
                                        <VipItemHeader
                                            className={this.state.vipServerSelect === current.serverId ? 'select' : null}>
                                            {/* 如果选择了此项，则会出现一个选中的样式 */}
                                            {
                                                this.state.vipServerSelect === current.serverId ?
                                                    <Config.IconFont type={'icon-choose'}
                                                                     style={selectIconStyle}/> : null
                                            }
                                            {/* 折扣或相关内容显示 */}
                                            {
                                                current.note ?
                                                    <span className={'note'}>
                                                    {current.note}
                                                </span> : null
                                            }
                                            {
                                                (() => {
                                                    switch (key) {
                                                        case '月卡':
                                                            unit = '月';
                                                            return <>
                                                                <p className={'item-1'}>
                                                                    <Config.IconFont type={'icon-huiyuan1'}
                                                                                     style={iconStyle}/>
                                                                    <label style={{float: 'left'}}>会员包月</label>
                                                                </p>
                                                                <p className={'item-2'}>
                                                                    <span
                                                                        className={'symbol'}>&yen;</span>{current.cost}<span
                                                                    className={'end-text'}> / {unit}</span>
                                                                </p>
                                                            </>
                                                        case '年卡':
                                                            unit = '年';
                                                            return <>
                                                                <p className={'item-1'}>
                                                                    <Config.IconFont type={'icon-huiyuan4'}
                                                                                     style={iconStyle}/>
                                                                    <label style={{float: 'left'}}>会员包年</label>
                                                                </p>
                                                                <p className={'item-2'}><span
                                                                    className={'symbol'}>&yen;</span>{current.cost}<span
                                                                    className={'end-text'}> / {unit}</span>
                                                                </p>
                                                            </>
                                                        case '终身卡':
                                                            unit = null;
                                                            return <>
                                                                <p className={'item-1'}>
                                                                    <Config.IconFont type={'icon-huiyuan2'}
                                                                                     style={iconStyle}/>
                                                                    <label style={{float: 'left'}}>永久VIP会员</label>
                                                                </p>
                                                                <p className={'item-2'}><span
                                                                    className={'symbol'}>&yen;</span>{current.cost}<span
                                                                    className={'end-text'}> / 不限</span>
                                                                </p>
                                                            </>
                                                    }
                                                })()
                                            }
                                            {/* 是否有优惠 */}
                                            {
                                                current.originalCost ?
                                                    <p className={'item-3'}>
                                                        原价:<span className={'symbol'}>&yen;</span>{current.originalCost}<span
                                                        className={'end-text'}>{unit ? `/${unit}` : null}</span>
                                                    </p>
                                                    :
                                                    null
                                            }
                                        </VipItemHeader>
                                    </VipItemContainer>
                                </Col>)
                            })
                            return nodes;
                        })()
                    }
                    <Col span={24}>
                        <h4 style={{color: '#666', padding: '0 5px'}}>
                            支付方式
                        </h4>
                    </Col>
                    <Col span={5}>
                        <PayContainer onClick={() => this.setState({payMethodSelect: 'c62778cc56664e1c'})}
                                      className={this.state.payMethodSelect === 'c62778cc56664e1c' ? "select" : null}
                        >
                            <Config.IconFont type={'icon-zhifubao1'} style={{fontSize: "15px"}}/>
                            <span>支付宝</span>
                        </PayContainer>
                    </Col>
                    <Col span={1}/>
                    <Col span={6}>
                        <PayContainer onClick={() => this.setState({payMethodSelect: '099ef3d7cbe6a8fe'})}
                                      className={this.state.payMethodSelect === '099ef3d7cbe6a8fe' ? "select" : null}
                        >
                            <Config.IconFont type={'icon-weixinzhifu'} style={{fontSize: "15px"}}/>
                            <span>微信支付</span>
                        </PayContainer>
                    </Col>
                    <Col span={24}>
                        <BtnContainer>
                            <Button size={"small"} style={{backgroundColor: "#5663a1"}}
                                    onClick={this.handlePayVipService}
                            >
                                <span style={{fontSize: '13px', color: '#fff', padding: '2px'}}>立即支付</span>
                            </Button>
                        </BtnContainer>
                    </Col>
                </Row>
            </VipServerContainer>
        </>
    }

    handleEdit() {
        editOnlineInfo(this.state.editFormData).then(res => {
            if (res.success) {
                successMsg("修改成功");
                this.setState({confirmType: null, confirmVisible: false});
                resetUserInfo();
            }
        })
    }


    editElementNode() {
        return <>
            <EditContainer>
                <Form
                    layout="horizontal"
                    ref={this.editForm}
                    name="validate_other"
                    labelCol={
                        {
                            'xs': {span: 24},
                            'sm': {span: 4},
                        }
                    }
                    wrapperCol={
                        {
                            xs: {span: 24},
                            sm: {span: 20},
                        }
                    }
                >
                    <Form.Item label={<span style={{fontWeight: 600}}>昵称</span>}
                               labelAlign={"left"}
                               name='onlineName'>
                        <Input value={this.state.editFormData.onlineName}
                               maxLength={32}
                               onChange={(e) => this.handleValueChange('onlineName', e)}
                        />
                    </Form.Item>

                    <Form.Item label={<span style={{fontWeight: 600}}>性别</span>}
                               labelAlign={"left"}
                               name='sex'>
                        <Row>
                            <Col span={5}>
                                <Config.IconFont type={'icon-nan'}
                                                 style={{fontSize: '30px', cursor: 'pointer'}}
                                                 onClick={() => this.handleValueChange('sex', 0)}
                                />
                                {
                                    this.state.editFormData.sex === 0 ?
                                        <Config.IconFont type={'icon-gou5'} style={{
                                            position: 'absolute',
                                            left: '2px',
                                            bottom: '-3px',
                                            fontSize: '30px',
                                            color: '#67dc3c'
                                        }}/>
                                        :
                                        null
                                }
                            </Col>
                            <Col span={5}>
                                <Config.IconFont type={'icon-nv'} style={{fontSize: '30px', cursor: 'pointer'}}
                                                 onClick={() => this.handleValueChange('sex', 1)}
                                />
                                {
                                    this.state.editFormData.sex === 1 ?
                                        <Config.IconFont type={'icon-gou5'} style={{
                                            position: 'absolute',
                                            left: '2px',
                                            bottom: '-3px',
                                            fontSize: '30px',
                                            color: '#67dc3c'
                                        }}/>
                                        :
                                        null
                                }
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item label={<span style={{fontWeight: 600}}>邮箱</span>}
                               labelAlign={"left"}
                               name='email'>
                        <Row gutter={[12, 12]}>
                            <Col span={15}>
                                <Input value={this.state.editFormData.email}
                                       onChange={(e) => this.handleValueChange('email', e)}
                                />
                            </Col>
                            <Col span={1}>
                                <Button style={{borderColor: '#43a0ff', color: '#43a0ff'}}
                                        disabled={this.state.emailCodeTimeOut !== null}
                                        onClick={this.handleSendEmailCode}>
                                    {
                                        this.state.emailCodeTimeOut === null ?
                                            "获取验证码" : `已发送(${this.state.emailCodeTimeOut}s)`
                                    }
                                </Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item label={<span style={{fontWeight: 600}}>验证码</span>}
                               labelAlign={"left"}
                               name='emailValidation'>
                        <Row gutter={[12, 12]}>
                            <Col span={15}>
                                <Input value={this.state.editFormData.emailValidation}
                                       placeholder={"请输入6位验证码"}
                                       onChange={(e) => this.handleValueChange('emailValidation', e)}
                                />
                            </Col>
                            <Col span={1}>
                                <Button type="primary"
                                        disabled={!this.state.editFormData.emailValidation}
                                        onClick={this.handleBindEmail}>
                                    绑定此邮箱
                                </Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item label={<span style={{fontWeight: 600}}>简介</span>}
                               labelAlign={"left"}
                               name='onlineText'>
                        <Input.TextArea value={this.state.editFormData.onlineText}
                                        placeholder={"用一句话介绍自己吧！"}
                                        maxLength={100} showCount
                                        rows={4}
                                        autoSize={{minRows: 4, maxRows: 4}}
                                        onChange={(e) => this.handleValueChange('onlineText', e)}
                        />
                    </Form.Item>
                    <Form.Item wrapperCol={{offset: 10, span: 24}}>
                        <Button type="primary" htmlType="submit" onClick={this.handleEdit}>
                            完成
                        </Button>
                    </Form.Item>
                </Form>
            </EditContainer>
        </>
    }

    handleOpenVipServer() {
        if (userVipType() === 3) {
            warnMsg("您已是永久会员，无需重复充值！");
            this.setState({confirmType: null, confirmVisible: false});
            return;
        }
        getVipServer().then(res => {
            if (res.success) {
                this.setState(
                    {
                        confirmType: 'vipServer',
                        confirmVisible: true,
                        vipServer: res.data
                    }
                );
            }
        })
    }

    handleClickEdit() {
        let editFormData = {
            onlineName: this.props.user.onlineName,
            sex: this.props.user.sex === '男' ? 0 : this.props.user.sex === '女' ? 1 : 2,
            email: this.props.user.email,
            onlineText: this.props.user.onlineText
        }

        this.setState({
            confirmVisible: true,
            editFormData,
            confirmType: 'edit',
        })
        /* 延时刷新数据 */
        setTimeout(() => {
            this.editForm.current.setFieldsValue(editFormData)
        }, 50)

    }

    render() {
        function customRequest(option) {
            const formData = new FormData();
            formData.append('image', option.file);
            Http({
                url: Api.UserUploadHeaderImage,
                method: 'post',
                processData: false,
                data: formData
            }).then(res => {
                if (res.success) {
                    UpdateUserImage(res.data);
                    // 更新缓存中的数据
                    sessionStorage.setItem('just-game-obj', toBase64(queryState('user')));
                    successMsg("更新头像成功")
                }
            });
        }

        const {fileList} = this.state
        const {user, UpdateUserImage} = this.props
        return (
            <HomeWrapper>
                <MineContainer>
                    <Row gutter={[32, 8]}>
                        <Col span={4}>
                            <LeftBar router={this.props.history}/>
                        </Col>
                        <Col span={19}>
                            <PersonalDataContainer>
                                <HeaderContainer>
                                    <ImageContainer>
                                        <Upload
                                            accept=".png,.jpg,.jpeg"
                                            customRequest={(op) => customRequest(op)}
                                            fileList={fileList}
                                            maxCount={'1'}
                                            onPreview={<>1</>}
                                        >
                                            <Tooltip
                                                title={<span style={{color: "#888", fontSize: '12px'}}>点击上传头像</span>}
                                                color={"white"}>
                                                <Avatar
                                                    className={'photo'}
                                                    style={{userSelect: "none"}}
                                                    src={user.images }
                                                    size={{xs: 150, sm: 150, md: 150, lg: 150, xl: 150, xxl: 150}}>
                                                    {user.uname}
                                                </Avatar>
                                            </Tooltip>
                                        </Upload>
                                    </ImageContainer>
                                    <AboutContainer>
                                        <Row gutter={[16, 20]}>
                                            {/* 用户昵称 */}
                                            <Col span={24}>
                                                <span className={'user-name'}>
                                                    {user.onlineName}
                                                </span>
                                                <div style={{cursor: 'pointer'}} onClick={this.handleOpenVipServer}>
                                                    <JVip/>
                                                </div>
                                            </Col>
                                            {/* 用户签名 */}
                                            <Col span={24}>
                                                <p className={'description'}>
                                                    <Config.IconFont type={'icon-shuangyinhao'}
                                                                     className={'double-quotation'}
                                                                     style={{fontSize: '12px'}}/>
                                                    {user.onlineText}
                                                    <Config.IconFont type={'icon-shuangyinhao1'}
                                                                     className={'double-quotation'}
                                                                     style={{fontSize: '12px'}}/>
                                                </p>
                                            </Col>
                                        </Row>
                                    </AboutContainer>
                                    <MoreInformationContainer>
                                        <Tooltip title={<span style={{
                                            color: "#888",
                                            fontSize: '12px'
                                        }}>{moment(user.finalDate, "YYYY-MM-DD hh:mm:ss").format("YYYY年MM月DD日 hh时mm分ss秒")}</span>}
                                                 color={"white"} placement={"right"}>
                                            <p>上次登陆时间：{user.finalDate ? moment(user.finalDate, "YYYY-MM-DD hh:mm:ss").fromNow() : "首次登录"}</p>
                                        </Tooltip>
                                        <p>
                                            <Button icon={<Config.IconFont type={'icon-xiugai'}/>} size={"small"}
                                                    onClick={this.handleClickEdit}>修改资料</Button>
                                        </p>
                                    </MoreInformationContainer>
                                </HeaderContainer>
                                {
                                    renderRoutes(this.props.route.routes)
                                }
                            </PersonalDataContainer>
                        </Col>
                    </Row>
                </MineContainer>
                {/* 修改资料时打开弹窗 */}
                <PolishConfirm visible={this.state.confirmVisible}
                               onCancel={() => this.setState({confirmType: null, confirmVisible: false})}
                >
                    {
                        (() => {
                            switch (this.state.confirmType) {
                                case 'edit':
                                    return this.editElementNode();
                                case 'vipServer':
                                    return this.vipServerElementNode();
                            }
                        })()
                    }
                </PolishConfirm>
            </HomeWrapper>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        user: state.getIn(['user']).toJS()
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        UpdateUserImage(url) {
            dispatch(UserAction.toUpdateUserImage(url));
        }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Mine);
